using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Xml;
using Microsoft.Win32;
using System.Xml.XPath;
using Microsoft.SharePoint.Client;
using MSDN.Samples.ClaimsAuth;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;


namespace CaptureLinks
{
    public partial class MainForm : System.Windows.Forms.Form
    {
        #region Public_Private Field
        string strSiteURL = "";
        //SPLinkLists.Lists listWS;
        string strLinkTitle = "";
        string strLinkURL = "";
        string strLinkDescription = "";
        bool check = false;
        #endregion

        #region CTOR
        public MainForm()
        {
            InitializeComponent();

        }
        #endregion

        #region Event Handlers
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                MessageBox.Show("0");
                StreamReader stream = new StreamReader(Application.StartupPath + "\\Link.xml", Encoding.UTF8);
                MessageBox.Show("1");
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(stream);
                MessageBox.Show("2");
                //Fill Selected Page Title 
                XmlNodeList Title = xmlDoc.GetElementsByTagName("Title");
                MessageBox.Show("3");
                strLinkTitle = Convert.ToString(Title[0].InnerText);
                MessageBox.Show(strLinkTitle);
                this.txtBox_Title.Text = strLinkTitle;

                //Fill Selected Page Url 
                XmlNodeList URL = xmlDoc.GetElementsByTagName("URL");
                strLinkURL = Convert.ToString(URL[0].InnerText);
                this.txtBoxSelectedLink.Text = strLinkURL;
                //Fill Selected Page Description 
                XmlNodeList Description = xmlDoc.GetElementsByTagName("Description");
                strLinkDescription = Convert.ToString(Description[0].InnerText);
                this.txtBox_Description.Text = strLinkDescription;

                //Fill SharePoint Site DropDown from settings.
                LoadSiteUrl();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            string strUrl = "";
            strUrl = this.cmbSiteUrl.Text;
            if (strUrl != "")
            {
                MessageBox.Show(strUrl + "...2");
                strSiteURL = this.cmbSiteUrl.Text;
                Fill_LinkListTree();
                //if(check == true)
                 btnAddLink.Enabled = true;
            }
            else
            {
                MessageBox.Show("SharePoint Site url can not be empty, Enter the Url and click Connect");
            }
        }

        private void btnAddLink_Click(object sender, EventArgs e)
        {
            check = AddNew_LinkListItem();
            if (check)
                MessageBox.Show("[" + strLinkTitle + "]added successfully!!!");
            else
                MessageBox.Show("Error-[" + strLinkTitle + "]could not be added, please check the List Name");
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_Settings_Click(object sender, EventArgs e)
        {
            CaptureLinksSettings.frmOptions objfrmOptions = new CaptureLinksSettings.frmOptions(null);
            objfrmOptions.ShowDialog();
        }

        #endregion

        #region Supporting Functions

        private void LoadSiteUrl()
        {
            string fileName = Application.StartupPath + "\\Options.xml";
            XPathDocument doc = new XPathDocument(fileName);
            XPathNavigator nav = doc.CreateNavigator();

            // Compile a standard XPath expression
            XPathExpression expr;
            expr = nav.Compile("//@SiteUrl");
            XPathNodeIterator iterator = nav.Select(expr);
            try
            {
                while (iterator.MoveNext())
                {
                    XPathNavigator nav2 = iterator.Current.Clone();
                    cmbSiteUrl.Items.Add(nav2.Value);
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void Fill_LinkListTree()
        {
            try
            {
                using (ClientContext context = ClaimClientContext.GetAuthenticatedContext(strSiteURL))
                {
                    context.Load(context.Web);

                    TreeNode listNode = new TreeNode("Link Lists");

                    Web oWebsite = context.Web;
                    context.Load(oWebsite);

                    ListCollection collList = oWebsite.Lists;

                    IEnumerable<List> resultCollection = context.LoadQuery(
                             collList.Include(
                                 list => list.Title,
                                 list => list.Id).Where(
                                     list => list.BaseTemplate == (int)ListTemplateType.Links
                                         && list.Hidden != true));

                    context.ExecuteQuery();

                    foreach (List oList in resultCollection)
                    {
                        listNode.Nodes.Add(oList.Title).ImageIndex = 4;
                    }
                    tv_LinkList.Nodes.Add(listNode);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("SharePoint Site url can not be empty, Enter the Url and click Connect");
                MessageBox.Show(ex.Message);
                
            }

        }

        private bool AddNew_LinkListItem()
        {
            try
            {
                using (ClientContext context = ClaimClientContext.GetAuthenticatedContext(strSiteURL))
                {
                    // Create an XmlDocument object and construct a Batch element and its attributes.
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    System.Xml.XmlElement batchElement = doc.CreateElement("Batch");

                    String strTitle = txtBox_Title.Text.ToString();
                    String strURL = txtBoxSelectedLink.Text.ToString();
                    //Create the URL in Url and Title form. 
                    strURL = strURL + ", " + strTitle;
                    String strDescription = txtBox_Description.Text.ToString();

                    List oList = context.Web.Lists.GetByTitle(tv_LinkList.SelectedNode.Text);
                    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                    ListItem oListItem = oList.AddItem(itemCreateInfo);
                    oListItem["URL"] = strURL;
                    oListItem["Comments"] = strDescription;
                    oListItem.Update();
                    context.ExecuteQuery();
                    check = true;
                    return check;
                }
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                check = false;
                return check;
            }

        }

        #endregion


    }
}